import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router';
import { useUserInfoStore } from '@/stores/userInfo';
import createDynamicRoute from './asyncRoutes';
import { useKeepAliveStore } from '@/stores/keepAlive';

/**
 * name:'router-name'            the name is used by <keep-alive> (must set!!!)
 * meta : {
    title: 'title'               the name show in tag-view (must set!!!)
    icon: 'icon-caiwu'           the icon show in the sidebar and top-header
    keepAlive: true              if set true, the page will be cached
    hidden: true                 if set true, item will not show in the sidebar
    noRequireAuth: true          if set true, Refers to pages that are independent of the app, usually displayed on page 404 without 
                                 permission authentication, without the need for login
    activeMenu: 'example-list'   if set route name, the sidebar will highlight the path you set
    noTagsView:                  if set true, the menu tag will not show in tag-view
    
  } 
 */

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 实现页签刷新页面的中间跳转页面
    {
      path: '/redirect',
      component: () => import('@/views/layout/index.vue'),
      name: 'Redirect',
      children: [
        {
          path: '/redirect/:path(.*)',
          name: 'redirect',
          component: () => import('@/views/redirect/index.vue'),
          meta: {}
        }
      ],
      meta: {
        hidden: true,
        noTagsView: true
      }
    },
    {
      // 测试页面项目开发中可以删除
      path: '/about',
      name: 'about',
      component: () => import('@/views/about/index.vue'),
      meta: {
        noRequireAuth: true,
        keepAlive: true
      }
    },
    {
      // 测试页面项目开发中可以删除
      path: '/http',
      name: 'http',
      component: () => import('@/views/http/index.vue'),
      meta: {
        noRequireAuth: true
      }
    }
  ]
});

interface DynamicObject {
  [key: string]: any;
}

router.beforeEach(async (to, from, next) => {
  // 读取权限认证中心登录之后url带的token,并存储起来，给后续接口headers用，前端url并去掉token
  if (to?.query?.token) {
    const token: string = to?.query?.token as string;
    localStorage.setItem('Authorization', token);
    const queryParams = to.query;
    delete queryParams.token;
  }

  // 如果为true 则缓存页面 添加到对应的路由级里面
  if (to.meta.keepAlive) {
    const keepStore = useKeepAliveStore();
    // 一级路由添加到一级视图里
    if (to.matched?.[0]) {
      keepStore.setKeepAlive(keepStore.firstKeepAliveRoute, to.matched?.[0]?.name as string);
    }
    // 二级 三级 四级路由添加到二级视图里
    if (to.matched?.[1]) {
      keepStore.setKeepAlive(keepStore.secondKeepAliveRoute, to.matched?.[1]?.name as string);
    }
    if (to.matched?.[2]) {
      keepStore.setKeepAlive(keepStore.secondKeepAliveRoute, to.matched?.[2]?.name as string);
    }
    if (to.matched?.[3]) {
      keepStore.setKeepAlive(keepStore.secondKeepAliveRoute, to.matched?.[3]?.name as string);
    }
  }

  // 根据Authorization 判断有没有登录
  // 为了演示，先注释掉登录，真实开发中把后面的 || true 要去掉
  const Authorization = localStorage.getItem('Authorization') || true;
  if (Authorization) {
    // 读取store里用户信息
    const store = useUserInfoStore();
    // 判断有没有用户信息 如果有放行，没有获取用户信息，生成路由

    if (!store.userInfo) {
      try {
        // 获取用户信息 包含页面路由
        const data = (await store.setUserInfo()) as DynamicObject;
        // 动态生成路由
        const asyncRoutesChildren = createDynamicRoute(data.menuTree ?? []) as RouteRecordRaw[];
        const asyncRoutes: RouteRecordRaw = {
          path: '/',
          name: 'layout',
          component: () => import('@/views/layout/index.vue'),
          children: [
            {
              path: '',
              name: 'home',
              component: () => import('@/views/home/index.vue'),
              meta: {
                title: '首页',
                noTagsView: true
              }
            },
            ...asyncRoutesChildren
          ]
        };
        router.addRoute(asyncRoutes);

        // 解决动态添加路由之后页面刷新404问题，把404页面添加到最后
        const notFoundRoutes: RouteRecordRaw = {
          path: '/:pathMatch(.*)*',
          name: 'notFound',
          component: () => import('../views/Notfound.vue'),
          meta: {
            noRequireAuth: true
          }
        };
        router.addRoute(notFoundRoutes);
        next({ ...to, replace: true });
      } catch (error) {
        console.log(error);
        next(false);
      }
    } else {
      next();
    }
  } else {
    // 不需要权限认证的 直接方行
    if (to?.meta?.noRequireAuth) {
      return next();
    }
    const store = useUserInfoStore();
    // 单独访问系统 没有token时调取用户信息，跳到权限中心登录
    if (!store.userInfo) {
      try {
        await store.setUserInfo();
      } catch (error) {
        console.log(error);
        next(false);
      }
      return next();
    }
  }
});

export default router;
